<template>
    <div :class="type == 1 ? 'login-method h340' : 'login-method'">
      <el-tabs v-model="activeName" type="card" >
        <el-tab-pane label="账号登录" name="pwd">
          <div class="pwd">
            <el-form :model="pwdForm" :rules="pwdFormRules" ref="pwdFormRef" class="pwd_form">
              <el-form-item prop="phone">
                <el-input placeholder="手机号" v-model="pwdForm.phone">
                  <div slot="prefix" class="phone_icon"></div>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input placeholder="密码" @keyup.enter.native="login('pwdFormRef')" type="password" v-model="pwdForm.password">
                  <div slot="prefix" class="pwd_icon"></div>
                </el-input>
              </el-form-item>
            </el-form>
            <div class="agreement clearfloat">
              <template  v-if="type == 2">
                <el-checkbox  v-model="isRead"></el-checkbox>
                <span>我已阅读且同意</span>
                <span class="btns" @click="agreement"><span>服务条款及</span><span>隐私协议</span></span>
                <div class="clearfloat mt10">
                  <el-checkbox v-model="autoLogin" class="fl autoLogin">自动登录</el-checkbox>
                  <el-button type="text" class="fr forgot_word ml10" @click="forgotPassword(5)">忘记密码</el-button>
                  <el-button type="text" class="fr register_now" @click="register">立即注册</el-button>
                </div>
              </template>
              <template  v-else>
                <el-checkbox v-model="autoLogin" class="fl autoLogin">自动登录</el-checkbox>
                <!-- <span>我已阅读相关</span>
                <span class="btns" @click="agreement"><span class="decoration">服务条款</span><i>及</i><span class="decoration">隐私协议</span></span>
                <el-checkbox class="ml10" v-model="isRead"></el-checkbox> -->
                <el-button type="text" class="fr forgot_word ml10" @click="forgotPassword(2)">忘记密码</el-button>
                <el-button type="text" class="fr register_now" v-no-more-click:3000 @click="register">立即注册</el-button>
              </template>
            </div>
            <el-button type="primary" @click="login('pwdFormRef')" class="login" :disabled="!isRead" v-no-more-click:3000>登录</el-button>
            <el-button class="application" v-if="type == 2" @click="$router.push('/user/apply')" v-no-more-click:3000>快速申请</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="验证码登录" name="code">
          <div class="code">
            <el-form :model="codeForm" :rules="codeFormRules" ref="codeFormRef" class="code_form" >
              <el-form-item prop="phone">
                <el-input placeholder="手机号" v-model="codeForm.phone">
                  <div slot="prefix" class="phone_icon"></div>
                </el-input>
                <el-button class="code_btns"  type="text" @click="getVCode('codeFormRef')" :disabled="btnIsDisabled">{{VCodeText}}</el-button>
              </el-form-item>
              <el-form-item prop="code">
                <!-- <el-input placeholder="验证码" v-model="codeForm.code" class="code_input" @keyup.enter.native="codeLogin('codeFormRef')">
                  <div slot="prefix" class="code_icon"></div>
                </el-input> -->
                <sixCaptchaInput ref="sixCaptchaInput" :code.sync="codeForm.code" @updateCode='updateCode' />
              </el-form-item>
            </el-form>
            <div class="agreement clearfloat ">
              <template  v-if="type == 2">
                <el-checkbox class="ml10" v-model="isRead"></el-checkbox>
                <span>我已阅读且同意</span>
                <span class="btns" @click="agreement"><span>服务条款及</span><span>隐私协议</span></span><br />
                <el-button type="text" class="fr forgot_word ml10" @click="forgotPassword(5)">忘记密码</el-button>
                <el-button type="text" class="fr register_now" v-no-more-click:3000 @click="register">立即注册</el-button>
              </template>
              <template  v-else>
                <!-- <el-checkbox class="ml10" v-model="isRead"></el-checkbox>
                <span>我已阅读相关</span>
                <span class="btns" @click="agreement"><span class="decoration">服务条款</span><i>及</i><span class="decoration">隐私协议</span></span> -->
                <el-button type="text" class="fr forgot_word ml10" @click="forgotPassword(2)">忘记密码</el-button>
                <el-button type="text" class="fr register_now" v-no-more-click:3000 @click="register">立即注册</el-button>
              </template>
            </div>
            <el-button type="primary" @click="codeLogin('codeFormRef')" class="login" :disabled="!isRead" v-no-more-click:3000>登录</el-button>
            <el-button class="application" v-if="type == 2" @click="$router.push('/user/apply')" v-no-more-click:3000>快速申请</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
      <agreement ref="agreement"></agreement>
    </div>
</template>

<script>
import aes from "~/util/aes.js";
import agreement from './components/agreement'
import sixCaptchaInput from '~/components/sixCaptcha-input'

export default {
  components: {
    agreement,
    sixCaptchaInput
  },
  data () {
    var validatePhone = function(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入手机号'));
      } else if (!(/^1[3456789]\d{9}$/.test(value))) {
        callback(new Error('请输正确的手机号'));
      } else {
        callback();
      }
    }
  
    return {
      activeName: 'pwd',
      codeForm: {
        phone: '',
        code: ''
      },
      pwdForm: {
        phone: '',
        password: ''
      },
      pwdFormRules: {
        phone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        password: [
          { required: true,  message: "请输入密码", trigger: 'blur' }
        ]
      },
      codeFormRules: {
        phone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        code: [
          {  message: "请输入验证码", trigger: 'blur' }
        ]
      },
      isRead: true,
      VCodeText: '发送验证码',
      btnIsDisabled: false,
      autoLogin: false

    }
  },
  watch: {
    
    // 自动登录
    autoLogin (newValue, oldValue) {
      if(process.client) {
        window.localStorage.setItem('autoLogin', JSON.stringify(newValue))
      }
      if (this.autoLogin) {
        this.rememberPassword = true
      }
    }
  },
  created () {
    // 记住密码，自动登录 单选框的值拿存起来的
    this.$nextTick( () => {
      if(process.client) {
        this.autoLogin = JSON.parse(window.localStorage.getItem('autoLogin'))
      }
    })
    //注册过来的则设置默认手机号码
    if (this.$route.params.phone) {
      this.pwdForm.phone = this.$route.params.phone;
      this.pwdForm.phone = this.$route.params.phone;
    }
    // 获取记住密码存储的用户账号密码
    if(process.client) {
      // 是否自动登录
      if(JSON.parse(window.localStorage.getItem('autoLogin'))) {
        let userInfo = JSON.parse(aes.Decrypt(window.localStorage.getItem('userInfo')))
        if(userInfo) {
          this.pwdForm.phone = userInfo.user
          this.pwdForm.password  = userInfo.password
        }
        this.$nextTick(() =>{
          this.login('pwdFormRef')
        })
      }
    }
  },
  computed: {
    type() {
      return this.$route.query.type
    }
  },
  methods: {
    // 密码登录
    login (formName) {
      console.log(this.$refs[formName])
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {
            phone: this.pwdForm.phone,
            password: this.pwdForm.password
          }
          let url = 'api/agent/login'
          if (this.type == 1) {
            this.agentLogin(url, params)
          } else if (this.type == 2) {
            url = '/api/auth/login'
            params.source = 'customer'
            this.userLogin(url, params)
          }
        } else {
          return false
        }
      })

    },
    // 代理人登录
    agentLogin (url, params) {
      this.$axios.post(url, params).then( res => {
        if (res.data.code == 200) {
          if (res.data.data.user.status == "待初审") {
            this.$alert('暂时无法登陆，请耐心等待审核员审核', '提示', {
              confirmButtonText: '确定',
              center: true,
              callback: action => {

              }
            })
          } else if ( res.data.data.user.status == "初审通过" || res.data.data.user.status == "已上传资料") {
            this.setLoginStatus(res.data.data)
            this.$router.push("/admin/agentImprove");
          } else {
            this.setLoginStatus(res.data.data)
            this.$router.push('/agent/home/menu')
          }
        } else {
          this.$alert(res.data.message, '提示', {
            confirmButtonText: '确定',
            center: true,
            type: 'warning',
            callback: action => {
            }
          })
        }
      })
    },
    // 用户登录
    userLogin (url, params) {
      this.$axios.post(url, params).then( res => {
        if (res.data.code == 200) {
          this.setLoginStatus(res.data.data)
          this.$router.push('/user/home/menu')
        } else {
          this.$alert(res.data.message, '提示', {
            confirmButtonText: '确定',
            center: true,
            type: 'warning',
            callback: action => {
            }
          })
        }
      })
    },
    // 验证码登录
    codeLogin (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {
            phone:this.codeForm.phone,
            code: this.codeForm.code
          }
          let url = '/api/agent/agentCodeLogin'
          if (this.type == 1) {
            this.agentLogin(url, params)
          } else if (this.type == 2) {
            url = '/api/consumer/codeLogin'
            this.userLogin(url, params)
          }
        } else {
          return false
        }
      })
    },
    // 设置登录状态
    setLoginStatus (data) {

      this.$cookies.remove("agent");
      this.$cookies.set("token", data.token);
      this.$store.commit("setToken", data.token);
      this.$axios.defaults.headers.common["Authorization"] =
        "Bearer " + data.token;
      this.$cookies.set(
        "user",
        aes.Encrypt(JSON.stringify(data.user))
      );
      this.$store.commit("setUser", data.user)

      if(this.autoLogin) {
        let userInfo = { user: this.pwdForm.phone, password:  this.pwdForm.password }
        this.$cookies.set('userInfo', userInfo)
        if(process.client) {
          window.localStorage.setItem('userInfo', aes.Encrypt(JSON.stringify(userInfo)))
        }
      }
    },
    // 获取验证码
    getVCode(formName) {
      this.$refs[formName].validateField('phone', valid => {
        if(!valid) {
          if (this.btnIsDisabled) {
          } else {
            this.getVCodeRequest()
          }
        } else {
          return false
        }
      })

    },
    getVCodeRequest () {
      let that = this;
      let params = {
        phone: this.codeForm.phone,
        type: 3,
        // guard:
      }
      that.$axios.post("/api/captcha",params).then(res => {
        if (res.data.code == 200) {
          that.$message({
            message: "验证码发送成功！",
            type: "success"
          })
          let num = 60;
          that.btnIsDisabled = true;
          let timer = setInterval(function() {
            that.VCodeText = num + "秒后可重新发送";
            num -= 1;
            if (num < 0) {
              that.VCodeText = "发送验证码";
              that.btnIsDisabled = false;
              clearInterval(timer);
            }
          }, 1000);
        } else {
          if (res.data.code == 400) {
            that.$message({
              message: res.data.message,
              type: "error"
            })

          } else {
            that.$message({
              message: "验证码发送失败！",
              type: "error"
            })
          }
        }
      })
    },
    // 打开协议
    agreement() {
      this.$refs['agreement'].isShow = true
    },
    // 立即注册
    register () {
      if (this.type == 1) {
        this.$router.push('/agentRegister')
      } else if (this.type == 2) {
        this.$router.push('/userRegister')
      }
    },
    // 忘记密码
    forgotPassword (type) {
      // 跳转忘记密码页面
      this.$router.push({
        path: '/forgotPassword',
        query: {
          type: type
        }
      })
    },
    updateCode(val) {
      console.log(val)
      this.codeForm.code = val
    }
  }
}
</script>

<style lang='less'>
  .login-method {
    width:549px;
    height: 400px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background:rgba(255,255,255,1);

    .el-tabs  {
      width: 100%;
      height: 100%;

      .el-tabs__header {
        border: none;
        margin: 0;
        .el-tabs__nav-scroll {
          .el-tabs__nav {
            width: 100%;
            border: none;
            .el-tabs__item {
              width: 50%;
              text-align: center;
              border: none;
              font-size: 15px;

              color: #fff;
              background:rgba(36,157,255,1);
            }
            .is-active {
             color:rgba(36,157,255,1);
             background: #fff;
            }
          }
        }
      }

      .el-form {
        width: 390px;
        margin: 45px auto 10px;

        .el-form-item {
          margin-bottom: 30px;
          position: relative;

        }
        .el-input {
          .el-input__inner {
            padding-left: 58px;
          }
          .el-input__prefix {
            left: 20px;
          }
        }
      }
      .pwd {
        .pwd_form {
          .el-form-item:last-child {
            margin-bottom: 10px;
            .el-form-item__error {
              padding-top: 1px;
            }
          }
          .phone_icon {
            width:16px;
            height:26px;
            background:url('../../assets/img/图标.png') no-repeat;
            background-position:-405px -287px;
            margin-top: 6px;
          }
          .pwd_icon {
            width:17px;
            height:26px;
            background:url('../../assets/img/图标.png') no-repeat;
            background-position:-458px -319px;
            margin-top: 6px;
          }
        }
      }
      .code {
        .code_form {
          .el-form-item:last-child {
            margin-bottom: 10px;
            .el-form-item__error {
              padding-top: 1px;
            }
          }

          .code_btns {
            position: absolute;
            right: 18px;
            bottom: 0px;
          }
          .phone_icon {
            width:16px;
            height:26px;
            background:url('../../assets/img/图标.png') no-repeat;
            background-position:-405px -287px;
            margin-top: 6px;
          }
          .code_icon {
            width:27px;
            height:17px;
            background:url('../../assets/img/图标.png') no-repeat;
            background-position:-399px -321px;
            margin-top: 10px;
          }
        }


      }
      .agreement {
        width: 390px;
        margin: 0 auto;
        font-size:12px;
        color:rgba(36,157,255,1);
        i {
          font-style:normal;
          text-decoration:none;
        }

        .decoration {
          border-bottom: 1px dashed rgba(36,157,255,1);
        }
        .btns {
          cursor: pointer;
        }

        .register_now {
          padding: 0;
          font-size: 12px;
          line-height: normal;
        }
        .forgot_word{
          padding: 0;
          font-size: 12px;
          line-height: normal;
        }
        .autoLogin {
          .el-checkbox__label {
            font-size: 12px;
            color:rgba(36,157,255,1);
          }
        }

      }
      .login {
        width: 390px;
        margin: 30px auto 0;
        display: block;
      }
      .application {
        width: 390px;
        margin: 20px auto 0;
        display: block;
        border:1px solid rgba(88,165,234,1);
        color:rgba(36,157,255,1);
      }
    }

  }
  .h340 {
    height: 340px;
  }
</style>
